"use client"

import { useState, useEffect } from "react"
import { cn } from "@/lib/utils"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Input
} from "@/components/ui/input"
import {
  Button
} from "@/components/ui/button"
import {
  History,
  Calendar,
  User,
  Filter,
  Download,
  Search,
  ArrowUpDown,
  Clock,
  FileText,
  CheckCircle,
  AlertTriangle,
  Info,
  Plus,
  Edit,
  Trash2
} from "lucide-react"

interface ProjectHistory {
  id: string
  projectId: string
  versionId: string
  action: string
  fromLevel1: string
  fromLevel2: string
  fromLevel3: string
  fromLevel4: string
  toLevel1: string
  toLevel2: string
  toLevel3: string
  toLevel4: string
  description: string
  userId: string
  createdAt: string
  user: {
    id: string
    name: string
    email: string
  }
}

interface HistoryViewerProps {
  projectId: string
  projectName: string
}

export function HistoryViewer({ projectId, projectName }: HistoryViewerProps) {
  const [histories, setHistories] = useState<ProjectHistory[]>([])
  const [loading, setLoading] = useState(true)
  const [filterAction, setFilterAction] = useState("all")
  const [filterUser, setFilterUser] = useState("all")
  const [dateRange, setDateRange] = useState("all")
  const [searchTerm, setSearchTerm] = useState("")
  const [sortBy, setSortBy] = useState("createdAt")
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc")

  useEffect(() => {
    fetchHistories()
  }, [projectId])

  const fetchHistories = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/projects/${projectId}/histories`)
      if (response.ok) {
        const data = await response.json()
        // 确保data是数组
        const historiesArray = Array.isArray(data) ? data : []
        setHistories(historiesArray)
      }
    } catch (error) {
      console.error('Error fetching histories:', error)
      // 设置一些默认的示例数据
      setHistories([])
    } finally {
      setLoading(false)
    }
  }

  const getActionIcon = (action: string) => {
    switch (action) {
      case 'CREATED':
        return <Plus className="h-4 w-4" />
      case 'UPDATED':
        return <Edit className="h-4 w-4" />
      case 'STATUS_CHANGED':
        return <ArrowUpDown className="h-4 w-4" />
      case 'VERSION_CREATED':
        return <FileText className="h-4 w-4" />
      case 'DELETED':
        return <Trash2 className="h-4 w-4" />
      default:
        return <Info className="h-4 w-4" />
    }
  }

  const getActionColor = (action: string) => {
    const actionColors: Record<string, string> = {
      'CREATED': 'bg-green-100 text-green-800',
      'UPDATED': 'bg-blue-100 text-blue-800',
      'STATUS_CHANGED': 'bg-purple-100 text-purple-800',
      'VERSION_CREATED': 'bg-yellow-100 text-yellow-800',
      'DELETED': 'bg-red-100 text-red-800'
    }
    return actionColors[action] || 'bg-gray-100 text-gray-800'
  }

  const getActionLabel = (action: string) => {
    const actionLabels: Record<string, string> = {
      'CREATED': '创建项目',
      'UPDATED': '更新项目',
      'STATUS_CHANGED': '状态变更',
      'VERSION_CREATED': '创建版本',
      'DELETED': '删除项目'
    }
    return actionLabels[action] || action
  }

  const getStatusChangeDisplay = (history: ProjectHistory) => {
    if (history.action !== 'STATUS_CHANGED') return null

    const fromStatus = [
      history.fromLevel1,
      history.fromLevel2,
      history.fromLevel3,
      history.fromLevel4
    ].filter(Boolean).join(' → ')

    const toStatus = [
      history.toLevel1,
      history.toLevel2,
      history.toLevel3,
      history.toLevel4
    ].filter(Boolean).join(' → ')

    if (fromStatus && toStatus) {
      return (
        <div className="text-sm text-gray-600 mt-1">
          {fromStatus} → <span className="font-medium text-purple-600">{toStatus}</span>
        </div>
      )
    }
    return null
  }

  // 获取唯一的用户列表
  const uniqueUsers = Array.from(new Set(histories.map(h => h.user?.name).filter(Boolean)))

  // 过滤和排序历史记录
  const filteredAndSortedHistories = histories
    .filter(history => {
      const matchesAction = filterAction === "all" || history.action === filterAction
      const matchesUser = filterUser === "all" || history.user?.name === filterUser
      const matchesSearch = searchTerm === "" || 
        history.description?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        history.user?.name?.toLowerCase().includes(searchTerm.toLowerCase())

      let matchesDate = true
      if (dateRange !== "all") {
        const historyDate = new Date(history.createdAt)
        const now = new Date()
        const daysDiff = Math.floor((now.getTime() - historyDate.getTime()) / (1000 * 60 * 60 * 24))
        
        switch (dateRange) {
          case "7d":
            matchesDate = daysDiff <= 7
            break
          case "30d":
            matchesDate = daysDiff <= 30
            break
          case "90d":
            matchesDate = daysDiff <= 90
            break
        }
      }

      return matchesAction && matchesUser && matchesSearch && matchesDate
    })
    .sort((a, b) => {
      const aValue = a[sortBy as keyof ProjectHistory]
      const bValue = b[sortBy as keyof ProjectHistory]
      
      if (sortBy === 'createdAt') {
        const aDate = new Date(a.createdAt).getTime()
        const bDate = new Date(b.createdAt).getTime()
        return sortOrder === 'asc' ? aDate - bDate : bDate - aDate
      }
      
      if (typeof aValue === 'string' && typeof bValue === 'string') {
        return sortOrder === 'asc' 
          ? aValue.localeCompare(bValue)
          : bValue.localeCompare(aValue)
      }
      
      return 0
    })

  const exportHistory = () => {
    const csvContent = [
      ['时间', '操作类型', '操作人', '描述', '状态变更'].join(','),
      ...filteredAndSortedHistories.map(history => [
        new Date(history.createdAt).toLocaleString(),
        getActionLabel(history.action),
        history.user?.name || '',
        history.description || '',
        history.action === 'STATUS_CHANGED' 
          ? `${[
              history.fromLevel1,
              history.fromLevel2,
              history.fromLevel3,
              history.fromLevel4
            ].filter(Boolean).join(' → ')} → ${[
              history.toLevel1,
              history.toLevel2,
              history.toLevel3,
              history.toLevel4
            ].filter(Boolean).join(' → ')}`
          : ''
      ].join(','))
    ].join('\n')

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `${projectName}_历史记录_${new Date().toISOString().split('T')[0]}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-sm text-gray-500">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 顶部工具栏 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">历史记录</h2>
          <p className="text-gray-500">项目: {projectName}</p>
        </div>
        <Button onClick={exportHistory} variant="outline">
          <Download className="mr-2 h-4 w-4" />
          导出记录
        </Button>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">总记录数</p>
                <p className="text-2xl font-bold">{histories.length}</p>
              </div>
              <History className="h-8 w-8 text-blue-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">状态变更</p>
                <p className="text-2xl font-bold">{histories.filter(h => h.action === 'STATUS_CHANGED').length}</p>
              </div>
              <ArrowUpDown className="h-8 w-8 text-purple-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">项目更新</p>
                <p className="text-2xl font-bold">{histories.filter(h => h.action === 'UPDATED').length}</p>
              </div>
              <Edit className="h-8 w-8 text-blue-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">版本创建</p>
                <p className="text-2xl font-bold">{histories.filter(h => h.action === 'VERSION_CREATED').length}</p>
              </div>
              <FileText className="h-8 w-8 text-yellow-600" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 筛选和搜索 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Filter className="h-5 w-5" />
            筛选和搜索
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            <div>
              <label className="text-sm font-medium text-gray-700">操作类型</label>
              <Select value={filterAction} onValueChange={setFilterAction}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部操作</SelectItem>
                  <SelectItem value="CREATED">创建项目</SelectItem>
                  <SelectItem value="UPDATED">更新项目</SelectItem>
                  <SelectItem value="STATUS_CHANGED">状态变更</SelectItem>
                  <SelectItem value="VERSION_CREATED">创建版本</SelectItem>
                  <SelectItem value="DELETED">删除项目</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div>
              <label className="text-sm font-medium text-gray-700">操作人</label>
              <Select value={filterUser} onValueChange={setFilterUser}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部人员</SelectItem>
                  {uniqueUsers.map(user => (
                    <SelectItem key={user} value={user}>{user}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            
            <div>
              <label className="text-sm font-medium text-gray-700">时间范围</label>
              <Select value={dateRange} onValueChange={setDateRange}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部时间</SelectItem>
                  <SelectItem value="7d">最近7天</SelectItem>
                  <SelectItem value="30d">最近30天</SelectItem>
                  <SelectItem value="90d">最近90天</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div>
              <label className="text-sm font-medium text-gray-700">排序方式</label>
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="createdAt">按时间</SelectItem>
                  <SelectItem value="action">按操作类型</SelectItem>
                  <SelectItem value="description">按描述</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div>
              <label className="text-sm font-medium text-gray-700">排序顺序</label>
              <Select value={sortOrder} onValueChange={(value: "asc" | "desc") => setSortOrder(value)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="desc">降序</SelectItem>
                  <SelectItem value="asc">升序</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <div className="mt-4">
            <label className="text-sm font-medium text-gray-700">搜索</label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="搜索描述或操作人..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 历史记录列表 */}
      <Card>
        <CardHeader>
          <CardTitle>历史记录列表</CardTitle>
        </CardHeader>
        <CardContent>
          {filteredAndSortedHistories.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>时间</TableHead>
                  <TableHead>操作类型</TableHead>
                  <TableHead>操作人</TableHead>
                  <TableHead>描述</TableHead>
                  <TableHead>状态变更</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredAndSortedHistories.map((history) => (
                  <TableRow key={history.id}>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Clock className="h-4 w-4 text-gray-400" />
                        <span>{new Date(history.createdAt).toLocaleString()}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getActionColor(history.action)}>
                        <div className="flex items-center gap-1">
                          {getActionIcon(history.action)}
                          {getActionLabel(history.action)}
                        </div>
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <User className="h-4 w-4 text-gray-400" />
                        <span>{history.user?.name || '未知'}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>
                        <p>{history.description || '无描述'}</p>
                        {getStatusChangeDisplay(history)}
                      </div>
                    </TableCell>
                    <TableCell>
                      {history.action === 'STATUS_CHANGED' && (
                        <div className="text-sm">
                          <div className="text-gray-500">
                            {[
                              history.fromLevel1,
                              history.fromLevel2,
                              history.fromLevel3,
                              history.fromLevel4
                            ].filter(Boolean).join(' → ')}
                          </div>
                          <div className="text-purple-600 font-medium">
                            ↓
                          </div>
                          <div className="text-purple-600 font-medium">
                            {[
                              history.toLevel1,
                              history.toLevel2,
                              history.toLevel3,
                              history.toLevel4
                            ].filter(Boolean).join(' → ')}
                          </div>
                        </div>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <div className="text-center py-12">
              <History className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无历史记录</h3>
              <p className="text-gray-500">尝试调整筛选条件或查看其他时间范围</p>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}